#include <time.h>
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
#include "Log.h"

static char lstrProName[256]={0};

LogTypeInfo gLogTypeInfo[] = 
{
	{1,"INFORMATION"},
	{2,"WARNING"},
	{3,"ERROR"},
	{4,"FAULT"},
	{0,"UNDEFINE"}
};

int SetProgrameName(char *ppstrProName)
{
	strcpy(lstrProName,ppstrProName);
}

int GetDateTime(char *ppstrDateTime)
{
	time_t ltimeSecond;   /*计数秒数*/
	struct tm *ltmDateTime; /*数据元素：年月日时分秒等*/
	char lstrDateTime[20];
	
	memset(lstrDateTime,0,sizeof(lstrDateTime));
	
	time(&ltimeSecond);
	ltmDateTime=localtime(&ltimeSecond);
	
	sprintf(lstrDateTime,"%04d%02d%02d%02d%02d%02d",ltmDateTime->tm_year+1900,ltmDateTime->tm_mon,ltmDateTime->tm_mday,ltmDateTime->tm_hour,ltmDateTime->tm_min,ltmDateTime->tm_sec);

	strcpy(ppstrDateTime,lstrDateTime);
}

int GetDate(char *ppstrDate)
{
	time_t ltimeSecond;   /*计数秒数*/
	struct tm *ltmDateTime; /*数据元素：年月日时分秒等*/
	char lstrDate[10];
	
	memset(lstrDate,0,sizeof(lstrDate));
	
	time(&ltimeSecond);
	ltmDateTime=localtime(&ltimeSecond);
	
	sprintf(lstrDate,"%04d%02d%02d",ltmDateTime->tm_year+1900,ltmDateTime->tm_mon,ltmDateTime->tm_mday);

	strcpy(ppstrDate,lstrDate);
}

int WriteLog(int liType,char *ppstrLog, ...)
{
	char lstrFileName[MAX_LOG_FILE_LEN];
	char lstrDateTime[20];
	char lstrDate[10];
	char lstrLog[MAX_LOG_LEN];
	char lstrLogFilePath[MAX_LOG_FILE_LEN];
	FILE * lfp;
	int li;
	
	/*add by zgx for param "..."*/
	va_list ap;
	char buff[65535] = "";
	char _TempBuff[65535] = "";
	va_start(ap, ppstrLog);
	vsnprintf(buff, sizeof(buff), ppstrLog, ap);
	strcat(_TempBuff, buff);
	va_end(ap);
	/*end add*/

	memset(lstrFileName,0,sizeof(lstrFileName));
	memset(lstrDateTime,0,sizeof(lstrDateTime));
	memset(lstrDate,0,sizeof(lstrDate));
	
	GetDate(lstrDate);
	GetDateTime(lstrDateTime);
	
	getcwd(lstrLogFilePath,MAX_LOG_FILE_LEN);
	
	//get whole log path name
	sprintf(lstrFileName,"%s/%s%s.log",lstrLogFilePath,lstrProName,lstrDate);
	
	for(li=0;gLogTypeInfo[li].liLogType!=0;li++)
	{
		if(liType==gLogTypeInfo[li].liLogType)
			break;
	}
	
	sprintf(lstrLog,"time:%s pid:%d [%s] [%s]\n",lstrDateTime,getpid(),gLogTypeInfo[li].pstrLogInfo,_TempBuff);
	
	printf("%s",lstrLog);
	
	lfp=fopen(lstrFileName,"a+");
	fwrite(lstrLog,strlen(lstrLog),1,lfp);
	fclose(lfp);
	
	return 0;
}
